package com.lyn.tool.utils;

import androidx.annotation.NonNull;

import com.lyn.plugin.utils.LogUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class CrashUtil implements Thread.UncaughtExceptionHandler {

    private Thread.UncaughtExceptionHandler exceptionHandler;

    private static class CrashUtilTypeClass {
        private final static CrashUtil instance = new CrashUtil();
    }

    public static CrashUtil getInstance() {
        return CrashUtilTypeClass.instance;
    }

    public void init() {
        exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        StringBuilder sb = new StringBuilder();
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        Throwable cause = e.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result).append("\n");
        LogUtil.e(sb.toString());

    }
}
